package cn.blu10ph.tools.web_ctrl;

import fi.iki.elonen.util.ServerRunner;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.io.Console;
import java.util.Random;

public class Main {

    public static void main(String[] args) {
        boolean is_open = true;

        WebSocketServer ws;
        do {
            try {
                System.out.println("探测本机IP:");
                Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
                InetAddress ip = null;
                while (allNetInterfaces.hasMoreElements())
                {
                    NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
//                    System.out.println(netInterface.getName());
                    Enumeration addresses = netInterface.getInetAddresses();
                    while (addresses.hasMoreElements())
                    {
                        ip = (InetAddress) addresses.nextElement();
                        if (ip != null && ip instanceof Inet4Address)
                        {
                            System.out.println(ip.getHostAddress());
                        }
                    }
                }
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }
            Console cnsl = null;
            String password = null;
            try {
                // creates a console object
                cnsl = System.console();
                if(cnsl!=null){
                    // read password into the char array
                    char[] password_char_array = cnsl.readPassword("请输入连接密码(直接回车退出程序): ");
                    password = new String(password_char_array);
                }else{
                    password = getRandomcode();
                }
            } catch (Exception ex) {
                // if any error occurs
                ex.printStackTrace();
            }
            System.out.println("password:"+password);
            if("".equals(password)){
                is_open = false;
                continue;
            }

//        ServerRunner.run(WebSocketServer.class);
            try {
                ws = new WebSocketServer(19090, password, true);
                ws.start();
                ServerRunner.run(HttpServer.class);
                ws.stop();
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }
        }while(is_open);
    }

    public static String getRandomcode() {
        Random random = new Random();
        Integer rannum = (int) (random.nextDouble() * (9999999 - 1000000 + 1)) + 1000000;// 获取随机数
        return rannum.toString();
    }

}
